package com.lwl.shua.class01;

import java.io.File;
import java.util.LinkedList;

/**
 * @author lwl
 * @Description 给你一个文件路径，判断其下有多少个文件
 * @date 2025/9/5 16:50
 */
public class Code02CountFiles {
    public static void main(String[] args) {
        String path = "/opt/homebrew";
        System.out.println(countFiles(path));
    }

    public static int countFiles(String filePath) {
        File root = new File(filePath);
        if (!root.isDirectory() && !root.isFile()) {
            return 0;
        }
        if (root.isFile()) {
            return 1;
        }

        LinkedList<File> stack = new LinkedList<>();
        stack.push(root);
        int res = 0;
        while (!stack.isEmpty()) {
            File folder = stack.pollLast();
            for (File file : folder.listFiles()) {
                if (file.isDirectory()) {
                    stack.addLast(file);
                } else if (file.isFile()) {
                    res++;
                }
            }
        }
        return res;
    }
}
